<template>
  <edit-card :title="title" :type="type" :loading="loading" @confirm="handleConfirm">
    <div class="content-box">
      <version-form ref="versionFromRef" title="" :type="type" />
    </div>
  </edit-card>
</template>

<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import { computed, onMounted, ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRoute, useRouter } from 'vue-router'

  import { algoDepotApi } from '@/services/api'

  import VersionForm from '../components/version-form.vue'

  const route = useRoute()
  const router = useRouter()

  const routeQuery = route.query as any
  const detailId = (route.params.id as string) || ''
  const { algorithmId } = routeQuery
  const type = (detailId ? 'edit' : 'add') as 'add' | 'edit'
  const title = computed(() => (type === 'add' ? '上传版本' : '编辑版本'))

  onMounted(() => {
    type === 'edit' && getDetailData(detailId)
  })

  // 获取版本详情
  const detailData = ref<any>({})
  const versionFromRef = ref()
  const { runAsync: getVersionDetail } = useRequest(algoDepotApi.getVersionDetail, {
    onSuccess: (res: any) => {
      detailData.value = res.data
      versionFromRef.value.setVersionFrom(detailData.value)
    }
  })
  const getDetailData = (id: string) => {
    getVersionDetail(id)
  }

  // 提交
  const { runAsync: addVersion } = useRequest(algoDepotApi.addVersion, {
    onSuccess: () => {
      message.success('操作成功')
      versionFromRef.value.resetFields()
      router.back()
    }
  })
  const { runAsync: updateVersion } = useRequest(algoDepotApi.updateVersion, {
    onSuccess: () => {
      message.success('操作成功')
      versionFromRef.value.resetFields()
      router.back()
    }
  })
  const loading = ref(false)
  const handleConfirm = async () => {
    try {
      await versionFromRef.value.getVersionFrom()
      loading.value = true
      let params = { ...versionFromRef.value.versionFrom, algorithmId }
      // 新增
      if (type === 'add') {
        addVersion(params, { isAddUid: true })
      }
      // 修改
      else {
        params = { ...params, id: detailId }
        updateVersion(params, { isAddUid: true })
      }
      loading.value = false
    } catch (error) {
      console.log(error)
      loading.value = false
    }
  }
</script>
